package awesome.site.loader.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CheckSum {
	
	/**
	 * Compute checksum for file on drive.
	 * 
	 * @param driveFile
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws FileNotFoundException
	 */
	public static String getCheckSum(Path driveFile) throws NoSuchAlgorithmException, FileNotFoundException{
		//get algorithm
		MessageDigest digest = MessageDigest.getInstance("MD5");
		//set up file input stream
		InputStream is = new FileInputStream(driveFile.toFile());				
		byte[] buffer = new byte[8192];
		int read = 0;
		
		try {
			//read in file from drive
			while( (read = is.read(buffer)) > 0) {
				digest.update(buffer, 0, read);
			}
			byte[] md5sum = digest.digest();
			BigInteger bigInt = new BigInteger(1, md5sum);
			return bigInt.toString(16); //truncate
		} catch(IOException e) {
			throw new RuntimeException("Unable to process file for MD5", e);
		} finally {
			try {
				is.close();
			}
			catch(IOException e) {
				throw new RuntimeException("Unable to close input stream for MD5 calculation", e);
			}
		}
	}
	
	/**
	 * Compute checksum for file in memory.
	 * 
	 * @param memoryFile
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws FileNotFoundException
	 */
	public static String getCheckSum(byte[] memoryFile) throws NoSuchAlgorithmException, FileNotFoundException{
		//get algorithm
		MessageDigest digest = MessageDigest.getInstance("MD5");
		//read in file from memory
		digest.update(memoryFile, 0, memoryFile.length);	
		byte[] md5sum = digest.digest();
		BigInteger bigInt = new BigInteger(1, md5sum);
		return bigInt.toString(16); //truncate
	}
}
